package com.nbgroup.pojo.common;

import com.nbgroup.pojo.Role;
import com.nbgroup.pojo.User;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class UserExportExcel {

    public void exportRole(List<User> users){
        // 创建一个新的工作簿
        XSSFWorkbook workbook1 = new XSSFWorkbook();

        // 创建一个新的工作表
        XSSFSheet sheet = workbook1.createSheet("Sheet1");
        XSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("用户编号");
        row1.createCell(1).setCellValue("用户名称");
        row1.createCell(2).setCellValue("用户昵称");
        row1.createCell(3).setCellValue("部门");
        row1.createCell(4).setCellValue("手机号码");
        row1.createCell(5).setCellValue("状态");
        row1.createCell(6).setCellValue("创建时间");

        try {
            int rowNum1 = 1;
            for (User user : users) {
                Row row = sheet.createRow(rowNum1++);
                row.createCell(0).setCellValue(user.getUserId());
                row.createCell(1).setCellValue(user.getNickName());
                row.createCell(2).setCellValue(user.getUserName());
                row.createCell(3).setCellValue(user.getDeptName());
                row.createCell(4).setCellValue(user.getPhonenumber());
                row.createCell(5).setCellValue(user.getStatus());
               row.createCell(6).setCellValue(user.getCreateTime().toString());
            }
        } catch (Exception e) {
            throw new RuntimeException("数据异常");
        }

        // 将工作簿写入文件
        UUID uuid = UUID.randomUUID();
        try (FileOutputStream fileOut = new FileOutputStream("D://user"+uuid+"表.xls")) {
            workbook1.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel文件已成功创建！");
    }

}
